package com.itheima;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * 个人练习生<P>
 * 现在有100 块钱 ,分成3个红包 ,一共有5个人去抢
 *
 * @author 小赫
 * <p>2025/3/16 17:30
 */
public class demo9ownerTest {


    private static final double TOTAL_AMOUNT = 100.0;
    private static final int NUM_PACKETS = 3;
    private static final int NUM_PEOPLE = 5;

    private static final List<Double> redPackets = new CopyOnWriteArrayList<>();
    private static final Random random = new Random();

    public static void main(String[] args) {
        // 生成红包
        generateRedPackets(TOTAL_AMOUNT, NUM_PACKETS);
        System.out.println("Generated red packets: " + redPackets);

        // 创建并启动线程
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < NUM_PEOPLE; i++) {
            Thread thread = new Thread(new Snatcher(i));
            threads.add(thread);
            thread.start();
        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 输出每个人抢到的红包
        for (int i = 0; i < NUM_PEOPLE; i++) {
            System.out.println("Person " + i + " snatched packets: " + Snatcher.snatchedPackets.get(i) +
                    " with total amount: " + Snatcher.snatchedPackets.get(i).stream().mapToDouble(Double::doubleValue).sum());
        }
    }

    private static void generateRedPackets(double totalAmount, int numPackets) {
        for (int i = 0; i < numPackets - 1; i++) {
            // 随机生成一个红包金额，范围在0到剩余金额之间
            double amount = random.nextDouble() * (totalAmount - (numPackets - i - 1) * 0.01) + 0.01;
            redPackets.add(amount);
            totalAmount -= amount;
        }
        redPackets.add(totalAmount);
    }

    static class Snatcher implements Runnable {
        private static final List<List<Double>> snatchedPackets = new CopyOnWriteArrayList<>();
        private static final Object lock = new Object();

        static {
            for (int i = 0; i < NUM_PEOPLE; i++) {
                snatchedPackets.add(new ArrayList<>());
            }
        }

        private final int personId;

        public Snatcher(int personId) {
            this.personId = personId;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    if (redPackets.isEmpty()) {
                        break;
                    }
                    // 抢到一个红包
                    double packet = redPackets.remove(0);
                    snatchedPackets.get(personId).add(packet);
                    System.out.println("Person " + personId + " snatched a packet of " + packet);
                }
            }
        }
    }
}